package com.lc.user.express.alipay;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.lc.user.express.BaseSecondActivity;
import com.lc.user.express.R;
import com.lc.user.express.app.AppContext;
import com.lc.user.express.httpserver.GetZhiFu;
import com.lc.user.express.my.AccountBalanceActivity;
import com.lc.user.express.utils.Logger;
import com.zcx.helper.http.AsyCallBack;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;


public class PayDemoActivity extends BaseSecondActivity {
    private Double jine;//金额
    private EditText et_money;
    private TextView tv_public;
    private String ordernumber = "";//返回的金额
    // 商户PID
    public static final String PARTNER = "2088421420255582";
    // 商户收款账号
    public static final String SELLER = "1571220526@qq.com";
    // 商户私钥，pkcs8格式
    public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ43/F+UQcPBxWY+\n" + "RpXnsxx7Tet9PBejIq2RgljjstXDsSR1W+vhCR0QHyPq+uI9KDQi6thSbmHLEOIj\n" +
            "/TvxTnOSBUIUf0WdjWV6djYkTzRFjIEFq7yvAW11gNqugfq8X4vbBY74Vkh7v/oa\n" +
            "vbS89g0B7M+qAWVyUQyYmdJhL3EHAgMBAAECgYAzV7GjBoZM0w2OvzjCnnymCnFf\n" +
            "sLUWao7vSh/FXqaC7c0HKrpYkh8V+kxQqIkfb38jZA1Xg3BkdbQV3l3n3Md7ANA5\n" +
            "y3tqMxLPP+JrauHgX8Tjlx382Dyijh7ehXBl4QYvxf3jyIo6VW0oVlZPdec/EfI+\n" +
            "iIcKpbUFZW5sTRshEQJBAMtvhDfZuG6HCZnsBzkGFhfYZ0iBlufCMr0k+28mFmRk\n" +
            "vIrQh1o1icoD6owelQ6ZTCqHJPkcTHCXo4Jaawq/zmkCQQDHGYtO50eZ+i9nCbdZ\n" +
            "ANR9Wh3OuGTyskL06gCWY/ovv/YVbrQrR1aihoJT+r45N7PQiDJFdDVk3lcPub5H\n" +
            "EjXvAkABHUhFIg0vlc/IpxFXD6B5Wvcd34/bDyZGAPjboALJY//gZsoHBXoOwDy9\n" +
            "rcE1RkOzi+/46V3F1B7SLPqfIXPZAkEAvyfNUqJHYpSMMndnq3JakUeWWsU7VrDE\n" +
            "DHUmvz2aFYJOeGFjZjIGAeD2/D4/qJvMbqh0664ZHZFDMXv6Li5TzQJBALjQEAZ4\n" +
            "uvs2PH4oRxlR6wVx8Ndcsj1OY837DDGpHwsKBXfZlX7sDyc9q6FFsKxHR3eFsqc+\n" +
            "jqdd/Hxj6v8hCvY=";
    // 支付宝公钥
    public static final String RSA_PUBLIC = "";
    private static final int SDK_PAY_FLAG = 1;
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);

                    // 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
                    String resultInfo = payResult.getResult();

                    String resultStatus = payResult.getResultStatus();

                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        Toast.makeText(cnt, "支付成功",
                                Toast.LENGTH_SHORT).show();


                    } else {
                        // 判断resultStatus 为非“9000”则代表可能支付失败
                        // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            Toast.makeText(cnt, "支付结果确认中",
                                    Toast.LENGTH_SHORT).show();

                        } else {
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            Toast.makeText(cnt, "支付失败",
                                    Toast.LENGTH_SHORT).show();

                        }
                    }
                    break;
                }

                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recharge);
        setTitle("充值");
        initView();
    }

    private void initView() {
        et_money = (EditText) findViewById(R.id.et_money);
        tv_public = (TextView) findViewById(R.id.tv_public);
        tv_public.setOnClickListener(PayDemoActivity.this);


        tv_public.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(et_money.getText().toString().toString())) {
                    Toast.makeText(cnt, "充值金额不能为空", Toast.LENGTH_SHORT).show();
                } else if (!TextUtils.isEmpty(et_money.getText().toString().trim()) && et_money.getText().toString().trim().contains(".") && (et_money.getText().toString().trim().length() - et_money.getText().toString().trim().indexOf(".") - 1 > 2)) {
                    Toast.makeText(cnt, "充值数额不对请重新输入", Toast.LENGTH_SHORT).show();
                } else if (!TextUtils.isEmpty(et_money.getText().toString().trim()) && Double.valueOf(et_money.getText().toString().trim()).intValue() <= 0 && et_money.getText().toString().startsWith("0")) {
                    Toast.makeText(cnt, "充值数额不对请重新输入", Toast.LENGTH_SHORT).show();
                }else if (!TextUtils.isEmpty(et_money.getText().toString().trim()) && et_money.getText().toString().startsWith("0")){
                    Toast.makeText(cnt, "充值数额不对请重新输入", Toast.LENGTH_SHORT).show();
                }
                else if (!TextUtils.isEmpty(et_money.getText().toString().trim()) && Double.valueOf(et_money.getText().toString().trim()).intValue()>=999999999){
                    Toast.makeText(cnt, "充值数额不对请重新输入", Toast.LENGTH_SHORT).show();
                }
                else {
                    jine = Double.valueOf(et_money.getText().toString().trim());
                    getServerData();
                }

            }
        });

    }

    /**
     * call alipay sdk pay. 调用SDK支付
     */
    public void alipay(String price) {
        if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE)
                || TextUtils.isEmpty(SELLER)) {
            Logger.print("car", "erro=" + "需要配置PARTNER | RSA_PRIVATE| SELLER");
            return;
        }
        String orderInfo = getOrderInfo(getResources().getString(R.string.app_name), "1", price);
        // 对订单做RSA 签名
        String sign = sign(orderInfo);
        try {
            // 仅需对sign 做URL编码
            sign = URLEncoder.encode(sign, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 完整的符合支付宝参数规范的订单信息
        final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
                + getSignType();

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造PayTask 对象
                PayTask alipay = new PayTask(PayDemoActivity.this);
                // 调用支付接口，获取支付结果
                String result = alipay.pay(payInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * get the sdk version. 获取SDK版本号
     */
    public void getSDKVersion() {
        PayTask payTask = new PayTask(this);
        String version = payTask.getVersion();
    }

    /**
     * create the order info. 创建订单信息
     */
    private String getOrderInfo(String subject, String body, String price) {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + PARTNER + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + ordernumber + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + subject + "\"";
        // 商品详情
        orderInfo += "&body=" + "\"" + body + "\"";
        // 商品金额
        orderInfo += "&total_fee=" + "\"" + price + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + "http://168tchy.com:802/index.php/Api/Alipay/notifyurl" + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";
        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";
        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";
        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";

        return orderInfo;
    }

    /**
     * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
     */
    private String getOutTradeNo() {
        SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
        Date date = new Date();
        String key = format.format(date);

        Random r = new Random();
        key = key + r.nextInt();
        key = key.substring(0, 15);
        return key;
    }

    /**
     * sign the order info. 对订单信息进行签名
     *
     * @param content 待签名订单信息
     */
    private String sign(String content) {
        return SignUtils.sign(content, RSA_PRIVATE);
    }

    /**
     * get the sign type we use. 获取签名方式
     */
    private String getSignType() {
        return "sign_type=\"RSA\"";
    }

    /**
     * 访问网络接口57:
     */
    public void getServerData() {

        new GetZhiFu(AppContext.myPreferences.getUid(), jine.toString(), new AsyCallBack<GetZhiFu.Info>() {
            @Override
            public void onSuccess(String toast, int type, final GetZhiFu.Info info) throws Exception {
                super.onSuccess(toast, type, info);
                ordernumber = info.ordernumber;
                alipay(String.format("%.2f", jine));
            }
        }).execute(cnt);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (AccountBalanceActivity.onRefreshData != null) {
            AccountBalanceActivity.onRefreshData.setData();
        }
    }
}
